﻿package com.zhengdongzulin.zuke.ext

import android.content.Context
import android.content.res.AssetManager
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.lang.StringBuilder
import java.math.BigDecimal
import java.math.BigDecimal.ROUND_HALF_UP
import java.text.SimpleDateFormat
import java.util.*


private val REGEX_MOBILE = "^[1][3,4,5,6,7,8][0-9]{9}\$"
private val REGEX_ID = "^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]\$"

/**
 * 检查手机号
 */
fun String.checkPhone(): Boolean {
    if (Regex(REGEX_MOBILE).matches(this)) {
        return true
    }
    return false
}
/**
 * 检查身份证
 */
fun String.checkId(): Boolean {
    if (Regex(REGEX_ID).matches(this)) {
        return true
    }
    return false
}

@Throws(IOException::class)
fun String.readFileFromAssets(context: Context?): String? {
    if (null == context || null == this) return null
    val am: AssetManager = context.getAssets()
    val input = am.open(this)
    val output = ByteArrayOutputStream()
    val buffer = ByteArray(1024)
    var len = 0
    while (input.read(buffer).also { len = it } != -1) {
        output.write(buffer, 0, len)
    }
    output.close()
    input.close()
    return output.toString()
}

/**
 * 时间戳转date
 */
fun String.stampToDate(): String =
        SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date(this.toLong()))

/**
 * 手机号中间4位密文展示
 */
fun String.ciphertextPhone(): String = this.substring(0, 3) + "****" + this.substring(7, 11)

/**
 * 格式化手机号
 * 格式为：+86 133 3333 3333
 */
fun String.formatPhone(): String {
    val head = this.substring(0, 3)
    val middle = this.substring(3, 7)
    val tail = this.substring(7, 11)
    return StringBuilder().append("+86")
            .append("\u0020")
            .append(head)
            .append("\u0020")
            .append(middle)
            .append("\u0020")
            .append(tail)
            .toString()
}

/**
 * 保留两位小数向上整
 */
fun Double.formatDouble2(): Double = BigDecimal(this).setScale(2, ROUND_HALF_UP).toDouble()



/**
 * 检查是否全为汉字
 */
fun String.isChinese(): Boolean {
    var n: Int
    n = 0
    if (!(19968 <= n && n < 40869)) {
        return true
    }
    return false
}



fun String.isChineses(): Boolean {
    val reg: String = "[\\u4e00-\\u9fa5]+"
    return this.matches(Regex(reg))
}
